package com.xxr.mom.ci.api.component.interceptor;

import cn.hutool.core.util.RandomUtil;
import com.xxr.mom.ci.api.component.util.IpUtils;
import com.xxr.mom.ci.common.log.LogTrace;
import com.xxr.mom.ci.common.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author natsuki_kining
 * traceId: 鏈路id
 * traceOrder： 鏈路調用次序
 * <p>
 * logId: 當前請求id
 */
@Slf4j
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {

    private final static String requestStartTime = "request-start-time";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(requestStartTime, System.currentTimeMillis());
        String traceId = request.getHeader(LogTrace.TRACE_ID);
        String traceOrder = request.getHeader(LogTrace.TRACE_ORDER);
        if (StringUtils.isBlank(traceOrder)) {
            traceOrder = "0";
        }
        int order = 0;
        try {
            order = Integer.parseInt(traceOrder);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (StringUtils.isBlank(traceId)) {
            traceId = RandomUtil.randomString(16);
        }
        ThreadContext.put(LogTrace.TRACE_ID, traceId);
        ThreadContext.put(LogTrace.TRACE_ORDER, order + "");
        ThreadContext.put(LogTrace.THIS_ID, RandomUtil.randomString(8));
        ThreadContext.put(LogTrace.TRACE_IP, IpUtils.getIpAddress(request));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            long startTime = (long) request.getAttribute(requestStartTime);
            long endTime = System.currentTimeMillis();
            long requestTime = endTime - startTime;
            log.info("请求结束。startTime:{}, endTime:{}, requestTime:{}", TimeUtil.timeStampToDate(startTime), TimeUtil.timeStampToDate(endTime), requestTime);
            ThreadContext.clearMap();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
